package com.example.qt.ptplatform.controller;
import com.example.qt.ptplatform.service.impl.UserServiceImpl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import com.example.qt.ptplatform.service.impl.DownloadServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.example.qt.ptplatform.utils.JsonResult;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.StrUtil;
import com.example.qt.ptplatform.service.impl.UserServiceImpl;
import com.turn.ttorrent.bcodec.BDecoder;
import com.turn.ttorrent.bcodec.BEValue;
import com.turn.ttorrent.bcodec.BEncoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "download")
public class DownloadController {

    @Autowired
    private DownloadServiceImpl downloadService;
    @Autowired
    private UserServiceImpl userService;

    @GetMapping("/getfile")
    public ResponseEntity<byte[]> downloadFile(
            @RequestParam("user_id") Integer userId,
            @RequestParam("torrent_id") Integer torrentId) {
        try {
            userService.updateLikedTorrentsAndTags(userId, torrentId, "download");
            JsonResult jsonResult = downloadService.downloadTorrent(userId, torrentId);

            if (!jsonResult.getResult()) {
                return ResponseEntity.badRequest().body(null);
            }

            File file = (File) jsonResult.getRows();
            BEValue data = BDecoder.bdecode(Files.newInputStream(file.toPath()));
            Map<String, BEValue> map = data.getMap();

            // 1. 获取原始 announce URL（如果存在）
            BEValue originalAnnounce = map.get("announce");

            // 2. 构造新的 announce-list（两个 tracker 同级）
            List<BEValue> announceList = new ArrayList<>();

            // 如果原本就有 announce-list，保留所有 tracker
            if (map.containsKey("announce-list")) {
                for (BEValue tier : map.get("announce-list").getList()) {
                    announceList.addAll(tier.getList()); // 展平所有层级的 tracker
                }
            }
            // 如果没有 announce-list，但存在 announce，则添加原始 announce
            else if (originalAnnounce != null) {
                announceList.add(originalAnnounce);
            }

            // 3. 添加新的 tracker（同级）
            String newTracker = StrUtil.format("http://192.168.145.13:8080/torrent/announce?user_id={}", userId);
            announceList.add(new BEValue(newTracker));

            // 4. 重新构造 announce-list（所有 tracker 放在同一层）
            List<BEValue> singleTier = new ArrayList<>();
            for (BEValue tracker : announceList) {
                singleTier.add(new BEValue(Arrays.asList(tracker))); // 每个 tracker 单独作为一层（但实际同级）
            }
            map.put("announce-list", new BEValue(singleTier));

            // 5. 可选：设置主 announce 为原始 URL 或新 URL
            if (originalAnnounce != null) {
                map.put("announce", originalAnnounce);
            }

            ByteBuffer encode_data = BEncoder.bencode(map);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .body(encode_data.array());
        } catch (IOException e) {
            return ResponseEntity.status(500).body(null);
        }
    }


    @GetMapping("/records")
    public JsonResult getDownloadRecords(@RequestParam("user_id") Integer userId,
                                         @RequestParam("page") Integer page,
                                         @RequestParam("per_page") Integer perPage) {
        // 调用服务层获取下载记录并返回分页结果
        return downloadService.getDownloadRecords(userId, page, perPage);
    }

    // 删除下载记录
    @DeleteMapping("/deleteRecords")
    public JsonResult deleteDownloadRecord(@RequestParam("user_id") Integer userId,
                                           @RequestParam("download_id") Integer downloadId) {
        // 调用服务层方法删除记录
        return downloadService.deleteDownloadRecord(userId, downloadId);
    }

}
